<template>
  <section class="add">
    <el-form ref="formRef" :model="form" label-width="80px">
      <el-form-item label="姓名">
        <el-input v-model="form.teacherName"></el-input>
      </el-form-item>
      <el-form-item label="学院">
        <el-input v-model="form.institute"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-input v-model="form.sex"></el-input>
      </el-form-item>
      <el-form-item label="电话号码">
        <el-input v-model="form.tel"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.pwd"></el-input>
      </el-form-item>
      <el-form-item label="身份证号">
        <el-input v-model="form.cardId"></el-input>
      </el-form-item>
      <el-form-item label="职称">
        <el-input v-model="form.type"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即创建</el-button>
        <el-button type="text" @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </section>
</template>

<script>
import { ref } from 'vue'; // 引入 ref 来创建响应式数据
import axios from 'axios'; // 引入 axios
import { useRouter } from 'vue-router'; // 引入 vue-router 用于页面跳转
import { ElMessage } from 'element-plus'; // 引入 Element Plus 消息提示组件

export default {
  setup() {
    const form = ref({
      teacherName: "",
      institute: "",
      sex: "",
      tel: "",
      pwd: "",
      cardId: "",
      type: "",
      role: 2,
    });

    const router = useRouter(); // 使用 vue-router

    // 提交表单
    const onSubmit = () => {
      axios({
        url: '/api/teacher',
        method: 'post',
        data: { ...form.value },
      })
        .then((res) => {
          if (res.data.code === 200) {
            ElMessage({
              message: '数据添加成功',
              type: 'success',
            });
            router.push({ path: '/index/teacherManage' });
          }
        })
        .catch((error) => {
          console.error('Error submitting form:', error);
          // 可以添加错误处理逻辑
        });
    };

    // 取消表单
    const cancel = () => {
      form.value = {
        teacherName: null,
        institute: null,
        sex: null,
        tel: null,
        pwd: null,
        cardId: null,
        type: null,
        role: 2,
      };
    };

    return {
      form,
      onSubmit,
      cancel,
    };
  },
};
</script>

<style lang="less" scoped>
.add {
  padding: 0px 40px;
  width: 400px;
}
</style>
